package com.niubi.yygh.msm.controller;


import com.niubi.yygh.common.result.R;
import com.niubi.yygh.msm.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import util.RandomUtil;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {
  @Autowired
  MsmService msmService;

  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  @GetMapping("send/{phone}")
  public R sendCode(@PathVariable String phone) {
    String code = redisTemplate.opsForValue().get(phone);
    if (!StringUtils.isEmpty(code)){
      return R.ok();
    }
    code = RandomUtil.getFourBitRandom();
    boolean isSuccess = msmService.sendDx(phone, code);
    if (isSuccess){
      redisTemplate.opsForValue().set(phone,code,2,TimeUnit.MINUTES);
      return R.ok();
    }else {
      return R.error().message("验证码发送失败");
    }
  }
}
